<?php

namespace App\Repositories;

use App\Models\DealModel;
use App\Models\OperateModel;
use App\Models\StrategyModel;
use App\Models\DateModel;

class StrategyRepository extends BaseRepository
{
    /**
     * @param $params
     * @return array[]
     */
    public function getFilter ($params) {
        $user = request()->user();
        $where = [];
        $where[] = [
            'admin_id', $user['id']
        ];
        if ($params['type']) {
            $where[] = [
                'type', $params['type']
            ];
        }
        if ($params['name']) {
            $where[] = [
                'name', 'like', '%' . $params['name'] . '%'
            ];
        }

        if (isset($params['success_rate'])) {
            $where[] = [
                'success_rate', $params['success_rate']
            ];
        }
        if (isset($params['profit_percent'])) {
            $where[] = [
                'profit_percent', $params['profit_percent']
            ];
        }
        return [
            'where' => $where,
        ];
    }

    /**
     * @param $params
     * @return array
     */
    public function getList ($params)
    {
        $filter = $this->getFilter($params);
        $list = $this->getListItems(StrategyModel::query(), $filter, $params['page_size'] ?? 20, [
            'id',
            'name',
            'desc',
            'market_env',
            'type',
            'success_rate',
            'trade_times',
            'profit_percent',
            'sort'
        ], 'page', [
            'sort' => 'desc',
            'id' => 'asc'
        ]);
        return $list;
    }

    /**
     * @param $id
     * @return false
     */
    public function getStrategyInfo($id)
    {
        $user = request()->user();
        if (empty($id)) {
            return false;
        }
        $strategy = StrategyModel::where('id', $id)
            ->where('admin_id', $user['id'])
            ->select('id', 'name', 'desc', 'type', 'sort', 'remark', 'market_env', 'best_holding_days')
            ->first();
        return $strategy;
    }


    /**
     * @param $desc
     * @param false $date
     * @return array|mixed|string|string[]
     */
    public function replaceStrategyParams ($desc, $date = false, $dateElliptical = true)
    {
        $dateDates = $this->getDates($desc);
        $descDates = $dateDates['dates'];
        $limit = $dateDates['dateNumber'];
        if ($limit > 0) {
            if (empty($date)) {
                $date = date('Y-m-d');
            }
            $dates = DateModel::where('date', '<=', $date)
                ->where('is_open', DateModel::IS_OPEN)
                ->orderby('date', 'desc')
                ->limit($limit)
                ->pluck('date')
                ->toArray();
            // 拼接替换的日期
            $replaceDates = [];
            foreach ($descDates as $key => $descDate) {
                $num = str_replace('$date', '', $descDate);
                if ($dateElliptical) {
                    $replace = str_replace(date('Y-'), '', $dates[$num - 1]);
                } else {
                    $replace = $dates[$num - 1];
                }
                $replaceDates[$key] = $replace;
            }
            return str_replace($descDates, $replaceDates, $desc);
        }
        return $desc;
    }

    /**
     * @param $desc
     * @return mixed
     */
    private function getDates ($desc)
    {
        $pattern = '/\$date[1-9]/'; // 匹配 $date1、$date2 和 $date3

        preg_match_all($pattern, $desc, $matches);
        $dates = $matches[0];
//        $dates = array_unique($dates);
        $maxNum = 0;
        foreach ($dates as $date) {
            $num = str_replace('$date', '', $date);
            if ($num > $maxNum) {
                $maxNum = $num;
            }
        }
        return [
            'dates' => $dates,
            'dateNumber' => $maxNum,
        ];
    }

    /**
     * @param $params
     * @return mixed
     */
    public function save ($params)
    {
//        var_dump('进来');
        return @$this->saveOrUpdate('StrategyModel', $params);
    }

    /**
     * @param $strategyId
     */
    public function updateEarningRate ($strategyId)
    {
        $user = request()->user();
        if ($strategyId) {
            $operateRepo = new OperateRepository();
            $successCount = $operateRepo->getSuccessCount($strategyId);
            $failCount = $operateRepo->getFailCount($strategyId);
            $totalCount = $successCount + $failCount;
            if ($totalCount == 0) {
                $totalCount = 1;
            }
            $successRate = $successCount / $totalCount * 100;
            $operateSumRate = OperateModel::where('admin_id', $user['id'])
                ->where('strategy_id', $strategyId)
                ->where('is_finished', OperateModel::IS_FINISHED)
                ->sum('real_rate');
            $operateCount = OperateModel::where('admin_id', $user['id'])
                ->where('strategy_id', $strategyId)
                ->where('is_finished', OperateModel::IS_FINISHED)
                ->count();
            $operateCount = empty($operateCount) ? 1 : $operateCount;
            $profitPercent = round($operateSumRate / $operateCount, 2);
            $rst = StrategyModel::where('admin_id', $user['id'])
                ->where('id', $strategyId)
                ->update([
                    'trade_times' => $operateCount,
                    'profit_percent' => $profitPercent,
                    'success_rate' => $successRate
                ]);
            return $rst;
        }
    }
}
